package com.robot.system.controller;

import com.robot.auth.entity.LoginUser;
import com.robot.auth.service.TokenService;
import com.robot.common.core.tool.R;
import com.robot.generator.MybatisPlusCodeGenerator;
import com.robot.generator.domain.TableDetail;
import com.robot.system.domain.entity.portTest;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Description:TODO
 * @author:qzg
 * @Date:2020-12-08 9:52
 */
@RestController
@AllArgsConstructor
@RequestMapping("")
public class LoginController {

    private TokenService tokenService;
    private portTest portTest;
    private TableDetail tableDetail;

    @Resource
    private AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public String login(@RequestBody LoginUser loginUser){

        tableDetail.setPackagePath("com.robot.admin");
        tableDetail.setTableName("sys_user");
        tableDetail.setModuleName("robot");
        // test();
        MybatisPlusCodeGenerator.create(tableDetail);

        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(loginUser.getUsername(),loginUser.getPassword()));
            return tokenService.createToken(loginUser);
        }
        catch (Exception e)
        {
            System.out.println(e);
            return "";
        }
    }

    /**
     * 获取当前登录用户
     */
    @GetMapping("/getLoginUserInfo")
    public R getLoginUserInfo(HttpServletRequest request){
        return R.data(tokenService.getLoginUser(request));
    }
}
